﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class _Default : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var see = Session["Username"];

            if (see == null)
            {
                Response.Redirect("Login.aspx");
            }

            if (!IsPostBack)
            {
                FillData();
            }
        }

        private void FillData()
        {
            var sql = string.Format("select * from Task");

            var dt = DbHelper.GetData(sql);

            GrdList.DataSource = dt;
            GrdList.DataBind();
        }

        private string GetVal(int rowIndex,int colIndex)
        {
            var control = GrdList.Rows[rowIndex].Cells[colIndex];
            var res = control.Controls.Count > 0 ? ((TextBox)control.Controls[0]).Text : control.Text;
            return res;
        }

        protected void GrdList_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {

        }

        protected void GrdList_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var id = GetVal(e.RowIndex, 0);

            var sql = string.Format("delete from Task where Id={0}", id);

            DbHelper.Exe(sql);

            FillData();
        }

        protected void GrdList_RowEditing(object sender, GridViewEditEventArgs e)
        {
            var id = GetVal(e.NewEditIndex, 0);
            Response.Redirect("TaskEdit.aspx?id="+id);
        }

        protected void GrdList_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {

        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            Response.Redirect("TaskEdit.aspx");
        }

        protected void GrdList_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GrdList.PageIndex = e.NewPageIndex;
            FillData();
        }
    }
}